package com.freshmarket.freshmarket.controller;


import com.freshmarket.freshmarket.controller.form.UserRegisterForm;
import com.freshmarket.freshmarket.entity.User;
import com.freshmarket.freshmarket.service.IUserService;
import com.freshmarket.freshmarket.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 *  前端控制器（用户）
 * </p>
 *
 * @author Squirrel
 * @since 2020-09-04
 */
@Controller
@RequestMapping("/freshmarket/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;
    /*用户注册*/
    @RequestMapping("register")
    @ResponseBody
    public Result register(@Validated UserRegisterForm userRegisterForm) throws Exception {
        Result register = userService.register(userRegisterForm);
        return register;
    }
    /*用户登录*/
    @RequestMapping("login")
    @ResponseBody
    public Result login(@RequestParam("userName")String userName,
                        @RequestParam("userPhone")String userPhone,
                        @RequestParam("userPassword")String userPassword,
                        HttpServletRequest request) throws Exception {

        log.info("电话:{}"+userPhone);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userPhone, userPassword);
        usernamePasswordToken.setRememberMe(true);
        subject.login(usernamePasswordToken);

        String nowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //记录当前用户的登录时间
        Result result = userService.recordTime(userPhone, nowDate);
        //Result result = iManagerService.updateManagerLoginTime(managerName, nowDate);
        return result;

    }
    @RequestMapping("islogin")
    @ResponseBody
    public Result islogin(HttpServletRequest request) throws Exception {
        User user = (User)request.getSession().getAttribute("user");
       // System.out.println("用户金额"+user.getUserMoney());

        return user == null ? new Result(false, 444, "未登录！", (Object)null) : new Result(true, 200, (String)null, user);
    }

    @RequestMapping("selectUser")
    @ResponseBody
    public Result selectUser(HttpServletRequest request) throws Exception {
        User user = (User) request.getSession().getAttribute("user");
        Result result = userService.selectUser(user.getUserId());
        return result;
    }

}

